from qiniu import Auth, put_file


class QiniuManage(object):
    def __init__(self, ak, sk, bucket_name):
        self.access_key = ak
        self.secret_key = sk
        self.bucket_name = bucket_name

    def _auth(self):
        q = Auth(self.access_key, self.secret_key)
        return q

    def upload_file(self, file_name, file_path):
        token = self._auth().upload_token(self.bucket_name, expires=3600 * 24 * 3)
        ret, info = put_file(token, key=file_name, file_path=file_path, version='v2')
        return ret, info

    def get_token(self):
        token = self._auth().upload_token(self.bucket_name, expires=3600 * 24 * 3)
        return token

    def download_file(self, key):
        bucket_addr = 'sf1ov1s7m.hb-bkt.clouddn.com'
        base_url = f'http://{bucket_addr}/{key}'
        private_url = self._auth().private_download_url(base_url, expires=3600 * 24 * 3)
        return private_url
